package com.zy.edu.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

/**
 * @Auther: HuangHaiShui
 * @Date: 2018/11/15 17:51
 * @Description:
 */
@Slf4j
public class FileUpload {

    /**
     *
     * @param file      上传的文件
     * @param folderName  统一的文件夹地址
     * @param module    该图片的模块文件夹名
     * @return
     */
    public static String writeUploadFile(MultipartFile file,String folderName, String module) throws IOException {
        String fileName = "";
        if (!file.isEmpty()) {
            File fileSourcePath = new File(folderName,module);
            if (!fileSourcePath.exists()) {
                fileSourcePath.mkdirs();
            }
            fileName = file.getOriginalFilename();
            String extname = FilenameUtils.getExtension(fileName);
            String allowImgFormat = "gif,jpg,jpeg,png";
            if (!allowImgFormat.contains(extname.toLowerCase())) {
                return null;
            }
            fileName = Math.abs(file.getOriginalFilename().hashCode()) + RandomUtils.createRandomString( 4 ) + "." + extname;

//                log.info("上传的文件名为：" + fileName);
            File outFile = new File(fileSourcePath ,fileName);
            file.transferTo(outFile);
            return File.separator +"upload"+File.separator+module+File.separator+ fileName;
        }else{
            throw  new IOException("文件不存在");
        }
    }
}
